/*
 *  Copyright 2016 http://www.kedacomframework.org
 *
 *  Licensed under the Apache License, Version 2.0 (the "License");
 *  you may not use this file except in compliance with the License.
 *  You may obtain a copy of the License at
 *
 *        http://www.apache.org/licenses/LICENSE-2.0
 *
 *  Unless required by applicable law or agreed to in writing, software
 *  distributed under the License is distributed on an "AS IS" BASIS,
 *  WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
 *  See the License for the specific language governing permissions and
 *  limitations under the License.
 *
 *
 */

package com.kedacom.ctsp.authz.oauth2.service.implicit;

import com.kedacom.ctsp.authz.oauth2.OAuth2ServerProperties;
import com.kedacom.ctsp.authz.oauth2.core.GrantType;
import com.kedacom.ctsp.authz.oauth2.entity.AccessToken;
import com.kedacom.ctsp.authz.oauth2.entity.Client;
import com.kedacom.ctsp.authz.oauth2.core.OAuth2Exception;
import com.kedacom.ctsp.authz.oauth2.service.AbstractAuthorizationService;
import org.springframework.beans.factory.annotation.Autowired;

import java.util.Set;

import static com.kedacom.ctsp.authz.oauth2.core.ErrorType.*;

/**
 * TODO 完成注释
 *
 * @author
 */
public class DefaultImplicitGranter extends AbstractAuthorizationService implements ImplicitGranter {

    @Autowired
    private OAuth2ServerProperties serverProperties;

    @Override
    public AccessToken requestToken(ImplicitRequest request) {
        String clientId = request.getClientId();
        Set<String> scope = request.getScope();

        assertParameterNotBlank(clientId, ILLEGAL_CLIENT_ID);

        Client client = getClient(clientId);
        assertGrantTypeSupport(client, GrantType.IMPLICIT);
        if (scope == null || scope.isEmpty()) {
            scope = client.getSupportGrantScope();
        }
        if (!client.getSupportGrantScope().containsAll(scope)) {
            throw new OAuth2Exception(SCOPE_OUT_OF_RANGE);
        }
        if (!client.getRedirectUri().equals(request.getRedirectUri())) {
            throw new OAuth2Exception(ILLEGAL_REDIRECT_URI);
        }

        AccessToken accessToken = accessTokenService.createToken();
        accessToken.setGrantType(GrantType.IMPLICIT);
        accessToken.setScope(scope);
        accessToken.setOwnerId(request.getUserId());
        accessToken.setExpiresIn(serverProperties.getAccessTokenExpireSeconds());
        accessToken.setClientId(clientId);
        return accessTokenService.saveOrUpdateToken(accessToken);
    }
}
